import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController, ViewController } from 'ionic-angular';
import { BLE } from '@ionic-native/ble';
import { DialogProvider } from '../../providers/dialog/dialog';
import { BleProvider } from '../../providers/ble/ble';
import { Device } from '@ionic-native/device';
import { DeviceInfoDataService } from '../../providers/service/deviceInfo-data.service';
import { EventProvider } from '../../providers/event/event';
import { LoadingController, Loading } from 'ionic-angular';
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { CCPeriodDataService } from '../../providers/service/cCPeriod-data.service';

/**
 * Generated class for the DeviceSelectPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-device-select',
  templateUrl: 'device-select.html',
})
export class DeviceSelectPage {
  // 站点信息
  site = {
    charging_pile_name: null,
    cell_name: null,
    map_positioning: null,
    coordinate_info: null,
    address: null,
    supplementary_info: null,
    delivery_time: null,
    ammeter_code: null,
    province: null,
    city: null,
    area: null,
    charging_pile_id: null,
    business_subjec_name: null,
    property_company_name: null,
    charging_unit_List: [],
    charge_uprice_List: [],
  };

  // 设备信息
  charging_unit_List: Charging_unit_List[] = new Array<Charging_unit_List>();

  // 用户信息
  userInfo: login_info = new login_info();

  // 时间参数
  time = {
    dot_connect_time: 0,
    abnormal_last_time: 0,
  };
  
  max: any;
  maxVal:any;
  minValue:any;
  
  interval: any;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public ble: BleProvider,
    public dialog: DialogProvider,
    public cordova_plugin_device: Device,
    public modalCtrl: ModalController,
    public viewCtrl: ViewController,
    public deviceInfo: DeviceInfoDataService,
    public event: EventProvider,
    public loadingCtrl: LoadingController,
    public user: UserInfoProvider,
    public cCPeriod: CCPeriodDataService
  ) {
  }

  async ionViewDidLoad() {
    console.log('ionViewDidLoad DeviceSelectPage');
    this.userInfo = this.user.getuserInfo();
    this.investigationBLE();
    this.interval = setInterval(() => {
      for (const iterator of this.charging_unit_List) {
        if ( parseInt(iterator.remaining_time) > 0) {
          // this.dialog.showAlert(JSON.stringify(iterator.remaining_time), '');
          iterator.remaining_time = iterator.remaining_time - 1;
        }
        if ( parseInt(iterator.chargingtime) <parseInt(iterator.chargingtimerequest)) {
//           this.dialog.showAlert(JSON.stringify(iterator.chargingtime), '');
          iterator.chargingtime = iterator.chargingtime + 1;
        }
      }
    }, 60000);
    let data = await this.cCPeriod.find((a) => a.key !== '');
    this.time = data[0];
    this.max="100";
    this.maxVal = "100";
    this.minValue = "0";
    // console.log(this.charging_unit_List);
  }

  ionViewWillEnter() {
    // this.bleScan = setInterval((res) => {
    //   this.ble.scan().then((res) => {
    //     this.investigationBLE();
    //   });
    // },3000);
  }

  ionViewDidEnter() {
    this.ble.disconect();
    this.event.bindEvents(this.event.EVENT_BLEdevice, (res) => {
      let device = res['device'];
      if (this.cordova_plugin_device.platform === 'Android') {
        for (let i = 0; i < this.charging_unit_List.length; i++) {
          // this.charging_unit_List[i].switchBle = false;
          if (this.charging_unit_List[i].mac_code === device.id) {
            this.charging_unit_List[i].chargingtimerequest = device.chargingtimerequest;
            this.charging_unit_List[i].chargingtime = device.chargingtime;
            this.charging_unit_List[i].work_status = device.work_status;
            this.charging_unit_List[i].use_status = device.use_status;
            this.charging_unit_List[i].discharge_status = device.discharge_status;
            this.charging_unit_List[i].remaining_time = device.chargingtimerequest - device.chargingtime;
            if (device.work_status === '0') {
              if (device.use_status === '0') {
                if (device.discharge_status === '1') {
                  if (parseInt(this.userInfo.member_id) === parseInt(device.abnormal_user)) {
                    this.charging_unit_List[i].switchBle = true;
                  } else {
                    this.charging_unit_List[i].switchBle = false;
                    if ((this.time.dot_connect_time - (this.time.abnormal_last_time - device.continuechargetime)) > 0) {
                      this.charging_unit_List[i].remaining_time = this.time.dot_connect_time - (this.time.abnormal_last_time - device.continuechargetime);
                    } else {
                      this.charging_unit_List[i].remaining_time = 0;
                      this.charging_unit_List[i].switchBle = true;
                    }
                  }
                } else {
                  this.charging_unit_List[i].switchBle = true;
                }
              } else {
                this.charging_unit_List[i].switchBle = false;
              }
              this.charging_unit_List[i].device = device;
            } else {
              this.charging_unit_List[i].switchBle = false;
              this.charging_unit_List[i].device = device;
            }
            // this.dialog.showAlert(JSON.stringify(device.name), JSON.stringify(this.charging_unit_List[i]));




            // if (device.use_status === '0' && device.work_status === '0') {
            //   if (device.discharge_status === '1') {
            //     if (parseInt(this.userInfo.member_id) === parseInt(device.abnormal_user)) {
            //       this.charging_unit_List[i].switchBle = true;
            //     } else {
            //       this.charging_unit_List[i].switchBle = false;
            //       this.charging_unit_List[i].remaining_time = device.continuechargetime - this.time.dot_connect_time;
            //     }
            //   } else {
            //     this.charging_unit_List[i].switchBle = true;
            //   }
            //   this.charging_unit_List[i].device = device;
            // }
          }
          // this.dialog.showAlert(JSON.stringify(this.charging_unit_List[i]), 'JSON.stringify(device');
        }
      }
      if (this.cordova_plugin_device.platform === 'iOS') {
        for (let i = 0; i < this.charging_unit_List.length; i++) {
          // this.charging_unit_List[i].switchBle = false;

          if (this.charging_unit_List[i].mac_code === device.mac) {
            this.charging_unit_List[i].chargingtimerequest = device.chargingtimerequest;
            this.charging_unit_List[i].chargingtime = device.chargingtime;
            this.charging_unit_List[i].work_status = device.work_status;
            this.charging_unit_List[i].use_status = device.use_status;
            this.charging_unit_List[i].discharge_status = device.discharge_status;
            this.charging_unit_List[i].remaining_time = device.chargingtimerequest - device.chargingtime;

            if (device.work_status === '0') {
              if (device.use_status === '0') {
                if (device.discharge_status === '1') {
                  if (parseInt(this.userInfo.member_id) === parseInt(device.abnormal_user)) {
                    this.charging_unit_List[i].switchBle = true;
                  } else {
                    this.charging_unit_List[i].switchBle = false;
                    if ((this.time.dot_connect_time - (this.time.abnormal_last_time - device.continuechargetime)) > 0) {
                      this.charging_unit_List[i].remaining_time = this.time.dot_connect_time - (this.time.abnormal_last_time - device.continuechargetime);
                    } else {
                      this.charging_unit_List[i].remaining_time = 0;
                      this.charging_unit_List[i].switchBle = true;
                    }
                  }
                } else {
                  this.charging_unit_List[i].switchBle = true;
                }
              } else {
                this.charging_unit_List[i].switchBle = false;
              }
              this.charging_unit_List[i].uuid = device.id;
              this.charging_unit_List[i].device = device;
            } else {
              this.charging_unit_List[i].switchBle = false;
              this.charging_unit_List[i].uuid = device.id;
              this.charging_unit_List[i].device = device;
            }

            // if (device.use_status === '0' && device.work_status === '0') {
            //   if (device.discharge_status === '1') {
            //     if (parseInt(this.userInfo.member_id) === parseInt(device.abnormal_user)) {
            //       this.charging_unit_List[i].switchBle = true;
            //     } else {
            //       this.charging_unit_List[i].switchBle = false;
            //       this.charging_unit_List[i].remaining_time = device.continuechargetime - this.time.dot_connect_time;
            //     }
            //   } else {
            //     this.charging_unit_List[i].switchBle = true;
            //   }
            //   this.charging_unit_List[i].uuid = device.id;
            //   this.charging_unit_List[i].device = device;
            // }
          }
        }
      }
    });
  }

  ionViewWillLeave() {
    this.event.unbindEvents(this.event.EVENT_BLEdevice, {});
    clearInterval(this.interval);
    // this.event.unbindEvents(this.event.EVENT_BLEconnect, {});
    // clearInterval(this.bleScan);
  }

  async skipToTimeSelect(power) {
    if (power.switchBle) {
      if (this.cordova_plugin_device.platform === 'Android') {
        this.ble.selected(power.mac_code, power.device);
      };
      if (this.cordova_plugin_device.platform === 'iOS') {
        this.ble.selected(power.uuid, power.device);
      };
      this.ble.power_unit_id = power.power_unit_id

      this.navCtrl.push('TimeSelectPage', { power: power, charge_uprice_List: this.site.charge_uprice_List });



      // let modal = this.modalCtrl.create('TimeSelectPage', { power: power, charge_uprice_List: this.site.charge_uprice_List });
      // modal.onDidDismiss(data => {
      //   this.event.unbindEvents(this.event.EVENT_BLEconnect, {});
      //   if (data.code === 2) {
      //     this.navCtrl.push('ToPayPage', { power_unit_id: data.power_unit_id, charge_uprice: data.charge_uprice });
      //   } else {
      //     if (data.code === 1) {
      //       this.navCtrl.popToRoot();
      //     } else {
      //       if (data.code === 0){
      //         this.ble.disconect();
      //       }
      //     }
      //   }
      // });
      // modal.present();


    }else if(power.switchBle==false&&power.remaining_time>0){
    	this.dialog.showAlert('该充电桩无法使用',  power.remaining_time + '分钟后您可使用该设备');
    }else {
      // this.dialog.showAlert(JSON.stringify(power),'');
      this.dialog.showAlert('该充电桩无法使用', '');
    }

  }

  async investigationBLE() {
    this.site = this.navParams.get('data');
    this.charging_unit_List = this.site.charging_unit_List;
    for (let charging_unit_List_num = 0; charging_unit_List_num < this.charging_unit_List.length; charging_unit_List_num++) {
      this.charging_unit_List[charging_unit_List_num].switchBle = false;
      this.charging_unit_List[charging_unit_List_num].work_status = '';
      this.charging_unit_List[charging_unit_List_num].use_status = '';
      this.charging_unit_List[charging_unit_List_num].discharge_status = '';
    }
    // this.dialog.showAlert('charging_unit_List', this.charging_unit_List.length);
    if (this.cordova_plugin_device.platform === 'Android') {
      for (let i = 0; i < this.charging_unit_List.length; i++) {
        this.charging_unit_List[i].switchBle = false;
        for (let j = 0; j < this.ble.devices.length; j++) {
          if (this.charging_unit_List[i].mac_code === this.ble.devices[j].id) {
            this.charging_unit_List[i].chargingtimerequest = this.ble.devices[j].chargingtimerequest;
            this.charging_unit_List[i].chargingtime = this.ble.devices[j].chargingtime;
            this.charging_unit_List[i].work_status = this.ble.devices[j].work_status;
            this.charging_unit_List[i].use_status = this.ble.devices[j].use_status;
            this.charging_unit_List[i].discharge_status = this.ble.devices[j].discharge_status;
            this.charging_unit_List[i].remaining_time = this.ble.devices[j].chargingtimerequest - this.ble.devices[j].chargingtime;

            if (this.ble.devices[j].work_status === '0') {
              if (this.ble.devices[j].use_status === '0') {
                if (this.ble.devices[j].discharge_status === '1') {
                  if (parseInt(this.userInfo.member_id) === parseInt(this.ble.devices[j].abnormal_user)) {
                    this.charging_unit_List[i].switchBle = true;
                  } else {
                    this.charging_unit_List[i].switchBle = false;
                    if ((this.time.dot_connect_time - (this.time.abnormal_last_time - this.ble.devices[j].continuechargetime)) > 0) {
                      this.charging_unit_List[i].remaining_time = this.time.dot_connect_time - (this.time.abnormal_last_time - this.ble.devices[j].continuechargetime);
                    } else {
                      this.charging_unit_List[i].remaining_time = 0;
                      this.charging_unit_List[i].switchBle = true;
                    }
                  }
                } else {
                  this.charging_unit_List[i].switchBle = true;
                }
              } else {
                this.charging_unit_List[i].switchBle = false;
              }
              this.charging_unit_List[i].device = this.ble.devices[j];
            } else {
              this.charging_unit_List[i].switchBle = false;
              this.charging_unit_List[i].device = this.ble.devices[j];
            }

            // if (this.ble.devices[j].use_status === '0' && this.ble.devices[j].work_status === '0') {
            //   if (this.ble.devices[j].discharge_status === '1') {
            //     if (parseInt(this.userInfo.member_id) === parseInt(this.ble.devices[j].abnormal_user)) {
            //       this.charging_unit_List[i].switchBle = true;
            //     } else {
            //       this.charging_unit_List[i].switchBle = false;
            //       this.charging_unit_List[i].remaining_time = this.ble.devices[j].continuechargetime - this.time.dot_connect_time;
            //     }
            //   } else {
            //     this.charging_unit_List[i].switchBle = true;
            //   }
            //   this.charging_unit_List[i].device = this.ble.devices[j];
            // }
          }
        }
      }
    }
    if (this.cordova_plugin_device.platform === 'iOS') {
      for (let i = 0; i < this.charging_unit_List.length; i++) {
        this.charging_unit_List[i].switchBle = false;
        this.charging_unit_List[i].remaining_time = 0;
        for (let j = 0; j < this.ble.devices.length; j++) {
          if (this.charging_unit_List[i].mac_code === this.ble.devices[j].mac) {
            this.charging_unit_List[i].chargingtimerequest = this.ble.devices[j].chargingtimerequest;
            this.charging_unit_List[i].chargingtime = this.ble.devices[j].chargingtime;
            this.charging_unit_List[i].work_status = this.ble.devices[j].work_status;
            this.charging_unit_List[i].use_status = this.ble.devices[j].use_status;
            this.charging_unit_List[i].discharge_status = this.ble.devices[j].discharge_status;
            this.charging_unit_List[i].remaining_time = this.ble.devices[j].chargingtimerequest - this.ble.devices[j].chargingtime;

            if (this.ble.devices[j].work_status === '0') {
              if (this.ble.devices[j].use_status === '0') {
                if (this.ble.devices[j].discharge_status === '1') {
                  if (parseInt(this.userInfo.member_id) === parseInt(this.ble.devices[j].abnormal_user)) {
                    this.charging_unit_List[i].switchBle = true;
                  } else {
                    this.charging_unit_List[i].switchBle = false;
                    if ((this.time.dot_connect_time - (this.time.abnormal_last_time - this.ble.devices[j].continuechargetime)) > 0) {
                      this.charging_unit_List[i].remaining_time = this.time.dot_connect_time - (this.time.abnormal_last_time - this.ble.devices[j].continuechargetime);
                    } else {
                      this.charging_unit_List[i].remaining_time = 0;
                      this.charging_unit_List[i].switchBle = true;
                    }
                  }
                } else {
                  this.charging_unit_List[i].switchBle = true;
                }
              } else {
                this.charging_unit_List[i].switchBle = false;
              }
              this.charging_unit_List[i].uuid = this.ble.devices[j].id;
              this.charging_unit_List[i].device = this.ble.devices[j];
            } else {
              this.charging_unit_List[i].switchBle = false;
              this.charging_unit_List[i].uuid = this.ble.devices[j].id;
              this.charging_unit_List[i].device = this.ble.devices[j];
            }

            // if (this.ble.devices[j].use_status === '0' && this.ble.devices[j].work_status === '0') {
            //   if (this.ble.devices[j].discharge_status === '1') {
            //     if (parseInt(this.userInfo.member_id) === parseInt(this.ble.devices[j].abnormal_user)) {
            //       this.charging_unit_List[i].switchBle = true;
            //     } else {
            //       this.charging_unit_List[i].switchBle = false;
            //       this.charging_unit_List[i].remaining_time = this.ble.devices[j].continuechargetime - this.time.dot_connect_time;
            //     }
            //   } else {
            //     this.charging_unit_List[i].switchBle = true;
            //   }
            //   this.charging_unit_List[i].uuid = this.ble.devices[j].id;
            //   this.charging_unit_List[i].device = this.ble.devices[j];
            // }

          }
        }
      }
    }
  }

  refreshScan() {
    for (let i = 0; i < this.charging_unit_List.length; i++) {
      this.charging_unit_List[i].switchBle = false;
      this.charging_unit_List[i].work_status = '';
      this.charging_unit_List[i].use_status = '';
      this.charging_unit_List[i].discharge_status = '';
    }
    this.ble.scan(1);
  }
}


export class Site {
  charging_pile_name: any;
  cell_name: any;
  map_positioning: any;
  coordinate_info: any;
  address: any;
  supplementary_info: any;
  delivery_time: any;
  ammeter_code: any;
  province: any;
  city: any;
  area: any;
  charging_pile_id: any;
  business_subjec_name: any;
  property_company_name: any;
  charging_unit_List: any[];
  charge_uprice_List: any[];
}

export class Charging_unit_List {
  power_index: any; // 排序
  power_unit_id: any; // 供电设备id
  power_unit_code: any;
  states: any; // 状态,1：正常 0：顺坏 2：返修
  utility_time: any; // 最近使用时间
  mac_code: String;
  switchBle: any;
  uuid: any;
  device: Devices
  chargingtimerequest: any; // 申请时间
  chargingtime: any;// 实际实际 
  remaining_time: any; // 剩余时间
  work_status:any;
  use_status: any;
  discharge_status: any;
}

export class Devices {
  device_id: any;
  charger_times: any;
  work_minutes: any;
  device_status: any;
  uint_price1: any;
  continuechargetime: any;
  group_id: any;
  device_index: any;
  rc_total: any;
  chargingtimerequest: any;
  chargingtime: any;
  mac: any;
  cid: any;
  abnormal_user: any;
  work_status: any;
  use_status: any;
  discharge_status: any;
}

export class login_info {
  member_id: any;
  nickname: any;
  phone: any;
  balance: any;
  local_balance: any;
  member_state: any;
  created_at: any;
  updated_at: any;
  cuser_id: any;
  uuser_id: any;
  is_del: any;
  password: any;
  file_type_id: any;
  access_token: any;
  isAutomaticLogon: any;
}